package com.idlecode.service;

import cn.hutool.core.util.StrUtil;
import com.idlecode.bean.FieldTypeEntity;
import com.idlecode.bean.TableFieldEntity;
import com.idlecode.config.GenDataSource;
import com.idlecode.config.query.AbstractQuery;
import com.idlecode.config.template.GeneratorConfig;
import com.idlecode.config.template.ProjectInfo;
import com.idlecode.util.MyStringUtil;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: IdleCode
 * @description
 * @author: rongjuwei
 * @create: 2024-02-18 13:44
 **/
public class TableFieldService {

    public static List<TableFieldEntity> getTableFieldEntity(GenDataSource dataSource, String dataBaseName, String tableName) {
        // 获取原生字段数据
        List<TableFieldEntity> tableFieldList = getTableFieldList(dataSource, dataBaseName, tableName);
        /*try {
            //释放数据源
            dataSource.getConnection().close();
        } catch (SQLException e) {
            e.printStackTrace();
        }*/
        return tableFieldList;
    }

    /**
     * 获取表字段列表
     *
     * @param datasource 数据源
     * @param tableName  表名
     */
    public static List<TableFieldEntity> getTableFieldList(GenDataSource datasource, String dataBaseName, String tableName) {
        List<TableFieldEntity> tableFieldList = new ArrayList<>();
        try {
            AbstractQuery query = datasource.getDbQuery();
            String tableFieldsSql = query.tableFieldsSql(dataBaseName, tableName);
            PreparedStatement preparedStatement = datasource.getConnection().prepareStatement(tableFieldsSql);
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                TableFieldEntity field = new TableFieldEntity();
                field.setFieldName(rs.getString(query.fieldName()));
                String fieldType = rs.getString(query.fieldType());
                if (fieldType.contains(" ")) {
                    fieldType = fieldType.substring(0, fieldType.indexOf(" "));
                }
                field.setDataPrecision(rs.getInt(query.dataPrecision()));
                field.setDataScale(rs.getInt(query.dataScale()));
                field.setFieldType(fieldType);
                field.setFieldComment(rs.getString(query.fieldComment()));
                String key = rs.getString(query.fieldKey());
                field.setPrimaryPk(StrUtil.isNotBlank(key) && "PRI".equalsIgnoreCase(key));
                tableFieldList.add(field);
            }
            preparedStatement.close();
            rs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return tableFieldList;
    }

    public static void initFieldList(List<TableFieldEntity> tableFieldList, List<String> selectedGenFileItem, boolean isFormatException) throws Exception {
        // 字段类型、属性类型映射
        Map<String, FieldTypeEntity> fieldTypeMap = FieldTypeService.getMap();
        int index = 0;
        GeneratorConfig generatorConfig = new GeneratorConfig();
        // 获取基础字段
        ProjectInfo project = generatorConfig.getGeneratorConfig(selectedGenFileItem, isFormatException).getProject();
        List<String> baseFieldList = new ArrayList<>();
        String baseFieldStrs = project.getBaseFields();
        if (StrUtil.isNotBlank(baseFieldStrs)) {
            String[] baseFieldsSplit = baseFieldStrs.split(",");
            for (String baseFieldStr : baseFieldsSplit) {
                String trim = baseFieldStr.trim();
                if (StrUtil.isNotBlank(trim)) {
                    baseFieldList.add(trim);
                }
            }
        }
        for (TableFieldEntity field : tableFieldList) {
            String attrName = MyStringUtil.underlineToCamel(field.getFieldName());
            field.setAttrName(attrName);
            // 获取字段对应的类型
            FieldTypeEntity fieldTypeMapping = fieldTypeMap.get(field.getFieldType().toLowerCase());
            if (fieldTypeMapping == null) {
                // 没找到对应的类型，则为Object类型
                field.setAttrType("Object");
            } else {
                field.setAttrType(fieldTypeMapping.getAttrType());
                field.setPackageName(fieldTypeMapping.getPackageName());
            }
            field.setBaseField(baseFieldList.stream().anyMatch(baseField -> baseField.equals(attrName)));
            field.setMethodName(attrName.substring(0, 1).toUpperCase() + attrName.substring(1));
            field.setFormItem(true);
            field.setGridItem(true);
            field.setQueryType("=");
            field.setQueryFormType("text");
            field.setFormType("text");
            field.setSort(index++);
        }
    }
}
